<template>
  <div :class="['flex', 'justify-between', deviceDetection() && 'flex-wrap']">
    <div :class="[deviceDetection() ? ['w-full', 'mt-2'] : 'w-[calc(100%)]']">
      <el-form
        ref="formRef"
        :inline="true"
        :model="form"
        class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
      >
        <el-form-item label="资源名称：" prop="SearchTerm">
          <el-input
            v-model="form.SearchTerm"
            placeholder="请输入资源名称"
            clearable
            class="w-[180px]!"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            :loading="loading"
            @click="onSearch"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <PureTableBar title="" :columns="columns" @refresh="onSearch">
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog('创建')"
          >
            新增资源
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <div
            v-if="selectedNum > 0"
            v-motion-fade
            class="bg-[var(--el-fill-color-light)] w-full h-[46px] mb-2 pl-4 flex items-center"
          >
            <div class="flex-auto">
              <span
                style="font-size: var(--el-font-size-base)"
                class="text-[rgba(42,46,54,0.5)] dark:text-[rgba(220,220,242,0.5)]"
              >
                已选 {{ selectedNum }} 项
              </span>
              <el-button type="primary" text @click="onSelectionCancel">
                取消选择
              </el-button>
            </div>
            <el-popconfirm title="是否确认删除?" @confirm="onbatchDel">
              <template #reference>
                <el-button type="danger" text class="mr-1!">
                  批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
          <pure-table
            ref="tableRef"
            row-key="Id"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            align-whole="center"
            table-layout="auto"
            :loading="loading"
            :size="size"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="{ ...pagination, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @selection-change="handleSelectionChange"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('修改', row)"
              >
                编辑
              </el-button>
              <el-dropdown :hide-on-click="false">
                <el-button
                  class="ml-3! mt-[2px]!"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon('ep:more')"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-button
                        class="reset-margin"
                        link
                        type="danger"
                        :size="size"
                        :icon="useRenderIcon(Delete)"
                        @click.stop="handleDelete(row)"
                      >
                        删除
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        class="reset-margin"
                        link
                        type="success"
                        :size="size"
                        :icon="useRenderIcon(VideoPlay)"
                        @click="handlePlay(row)"
                      >
                        播放
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        class="reset-margin"
                        link
                        type="info"
                        :size="size"
                        :icon="useRenderIcon(Download)"
                        @click="handleDownload(row)"
                      >
                        下载
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>

  <!-- 播放预览对话框 -->
  <el-dialog
    v-model="playDialogVisible"
    title="资源播放"
    width="50%"
    :before-close="handlePlayDialogClose"
  >
    <div v-if="playDialogVisible && currentResource" class="play-container">
      <!-- 显示资源基本信息 -->
      <div class="resource-info mb-4 p-3 bg-gray-50 rounded">
        <p><strong>资源名称：</strong>{{ currentResource.Name }}</p>
        <p><strong>资源编号：</strong>{{ currentResource.Code }}</p>
        <p>
          <strong>资源类型：</strong>
          {{ currentResource.Type === 1 ? "普通音频文件" : "TTS" }}
        </p>
      </div>

      <!-- 音频播放器 - 针对所有类型资源显示 -->
      <div class="audio-player">
        <audio
          v-if="currentResource.uri"
          :src="currentResource.uri"
          controls
          style="width: 100%"
        />
        <div v-else-if="currentResource.Type === 1" class="text-danger">
          无法加载音频文件，请检查文件是否存在
        </div>
      </div>

      <!-- TTS内容 - 仅当类型为TTS时显示 -->
      <div
        v-if="currentResource.Type === 2"
        class="tts-content mt-4 p-4 bg-gray-100 rounded"
      >
        <p>
          <strong>TTS内容：</strong
          >{{
            currentResource.ttsContent || currentResource.Comment || "暂无内容"
          }}
        </p>
        <!-- TTS专用播放按钮 -->
        <el-button
          type="primary"
          :icon="useRenderIcon('ep:play')"
          class="mt-2"
          @click="handlePlayTTS"
        >
          播放TTS内容
        </el-button>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="playDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps } from "vue";
import { PureTable } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import VideoPlay from "~icons/ep/VideoPlay";
import Download from "~icons/ep/download";
import { useResourceTable } from "../componentsUtils/useResourceTable";
import { ElMessage } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

// 定义props
const props = defineProps<{
  lesseeId: number;
  dealerId: number;
  dealerName: string;
  tenantName: string;
}>();

const tableRef = ref();
const formRef = ref();
const playDialogVisible = ref(false);
const currentResource = ref<Record<string, any>>({});

const {
  form,
  loading,
  columns,
  dataList,
  selectedNum,
  pagination,
  deviceDetection,
  onSearch,
  resetForm,
  onbatchDel,
  openDialog,
  handleDelete,
  handleSizeChange,
  onSelectionCancel,
  handleCurrentChange,
  handleSelectionChange
} = useResourceTable(
  tableRef,
  props.lesseeId,
  props.dealerId,
  props.dealerName,
  props.tenantName
);

// 处理播放
const handlePlay = row => {
  // 深拷贝行数据，避免直接修改原数据
  currentResource.value = { ...row };

  // 根据资源类型构建不同的播放URL或处理方式
  if (row.Type === 1) {
    // 普通音频文件
    if (row.FileName) {
      currentResource.value.uri = changeHttpLink(`/api/File/${row.FileName}`);
    } else {
      ElMessage.warning("文件不存在，无法播放");
      return;
    }
  } else if (row.Type === 2) {
    // TTS文件 - 可以构建特殊的TTS播放URL或直接处理TTS内容
    if (row.Comment) {
      // 如果有Comment内容，可以直接用于TTS播放
      currentResource.value.ttsContent = row.Comment;
      // 也可以构建TTS播放的API URL（如果后端提供相关接口）
      if (row.FileName) {
        currentResource.value.uri = changeHttpLink(`/api/File/${row.FileName}`);
      }
    } else {
      ElMessage.warning("TTS内容不存在，无法播放");
      return;
    }
  }

  // 显示播放对话框
  playDialogVisible.value = true;
};
// 处理下载
const handleDownload = row => {
  if (!row.FileName) {
    ElMessage.error("下载链接不存在");
    return;
  }

  ElMessage.success(`开始下载资源: ${row.Name}`);

  // 使用正确的下载接口构建URL
  const fileKey = row.FileName;
  const downloadUrl = changeHttpLink(`/api/File/${fileKey}`);
  // 创建下载链接
  const link = document.createElement("a");
  link.href = downloadUrl;
  // 设置download属性为资源名称，确保下载的文件名正确
  link.download = row.Name || fileKey;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  ElMessage.success(`资源 ${row.Name} 下载成功`);
};

// 处理TTS播放
const handlePlayTTS = () => {
  if (!currentResource.value || !currentResource.value.ttsContent) {
    ElMessage.error("没有可播放的TTS内容");
    return;
  }

  const resourceName = currentResource.value.name || currentResource.value.Name;
  ElMessage.success(`开始播放TTS: ${resourceName}`);

  try {
    // 使用Web Speech API进行TTS播放
    if ("speechSynthesis" in window) {
      // 停止任何正在播放的语音
      window.speechSynthesis.cancel();

      // 创建语音合成实例
      const utterance = new SpeechSynthesisUtterance(
        currentResource.value.ttsContent
      );
      utterance.lang = "zh-CN"; // 设置为中文
      utterance.volume = 1; // 音量 (0-1)
      utterance.rate = 1; // 语速 (0.1-10)
      utterance.pitch = 1; // 音调 (0-2)

      // 设置播放结束回调
      utterance.onend = () => {
        ElMessage.success(`TTS播放完成: ${resourceName}`);
      };

      utterance.onerror = event => {
        console.error("TTS播放错误:", event);
        ElMessage.error(`TTS播放失败: ${event.error}`);
      };

      // 开始播放
      window.speechSynthesis.speak(utterance);
    } else {
      // 如果浏览器不支持Web Speech API，尝试使用audio标签播放
      if (currentResource.value.uri) {
        const audioElement = document.createElement("audio");
        audioElement.src = currentResource.value.uri;
        audioElement.play().catch(error => {
          console.error("音频播放错误:", error);
          ElMessage.error(
            "TTS播放失败，浏览器不支持Web Speech API且音频播放出错"
          );
        });
      } else {
        ElMessage.error("浏览器不支持Web Speech API，且没有可用的音频URL");
      }
    }
  } catch (error) {
    console.error("TTS播放异常:", error);
    ElMessage.error(`TTS播放异常: ${error.message}`);
  }
};

// 处理播放对话框关闭
const handlePlayDialogClose = () => {
  // 停止任何正在播放的TTS
  if ("speechSynthesis" in window) {
    window.speechSynthesis.cancel();
  }
  playDialogVisible.value = false;
};
</script>

<style scoped>
/* 调整操作列按钮样式 */
:deep(.el-table__cell) {
  .flex.space-x-2 {
    display: flex;
    gap: 8px;
  }
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.play-container {
  max-height: 400px;
  padding: 10px 0;
  overflow-y: auto;
}

.tts-content {
  min-height: 100px;
  border: 1px solid #e4e7ed;
}

.resource-info {
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
}

.audio-player {
  margin: 10px 0;
}
</style>
